//
//  MyViewShopController.m
//  UsersShop
//
//  Created by W_L on 2019/5/5.
//  Copyright © 2019 dwj. All rights reserved.
//

#import "MyViewShopController.h"
#import "ZHMyItemTableViewCell.h"
#import "ZHMyTableHeaderView.h"
#import "UIView+DBExtension.h"

#import "StroeMessageViewController.h"
#import "ReceivingOrderViewController.h"
#import "MessgerSettingViewController.h"
#import "Account.h"
#import "JPUSHService.h"
#import "AddNotice.h"
#import "SettlementInformationViewController.h"

@interface MyViewShopController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *mainTableView;

@property (nonatomic,strong) UIView *footView;
@property (nonatomic,strong) UIButton *exitBtn;
@property (nonatomic,strong) NSDictionary *dataArr;
@property (nonatomic, strong) ZHMyTableHeaderView *HeaderView;
@property (nonatomic, copy) NSString *gongGaoStr;
@property (nonatomic,strong) NSDictionary *dataDic;

@end

@implementation MyViewShopController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(!self.Identity.userInfo.isLogin){
        UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:[[Login alloc]init]];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        [self getData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    [self.mainTableView reloadData];
    self.dataArr = @{
                     @"section1":@[
                                    @{
                                    @"title":@"当前账号",
                                    @"img":@"账号"
                                    },
                                @{
                                    @"title":@"我的钱包",
                                    @"img":@"zh_qianbao"
                                    },
                                  @{
                                    @"title":@"联系业务经理",
                                    @"img":@"zh_lianxi"
                                    }
                                  ],
                     @"section2":@[
                                  @{
                                    @"title":@"门店设置",
                                    @"img":@"zh_mendian"
                                    },
                                  @{
                                    @"title":@"接单设置",
                                    @"img":@"zh_jiedan"
                                    },
                                  @{
                                    @"title":@"打印机",
                                    @"img":@"zh_dayin"
                                    },
                                  @{
                                    @"title":@"消息设置",
                                    @"img":@"zh_xiaoxi"
                                    }
                         ]
                    
                     };

}
- (void)initView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.mainTableView];
    
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    self.mainTableView.estimatedRowHeight = 33;
    
    self.mainTableView.rowHeight = UITableViewAutomaticDimension;
    
    
    
    if (@available(iOS 11.0, *)) {
        
        self.mainTableView.estimatedSectionFooterHeight = 0.1;
        
        self.mainTableView.estimatedSectionHeaderHeight = 0.1;
    }
//    self.mainTableView.estimatedRowHeight = 33;
//    self.mainTableView.rowHeight = UITableViewAutomaticDimension;
//        if (@available(iOS 11.0, *))
//        {
//            self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//
//            self.mainTableView.estimatedSectionFooterHeight = 0.1;
//            self.mainTableView.estimatedSectionHeaderHeight = 0.1;
//        }else{
//            self.automaticallyAdjustsScrollViewInsets = YES;
//        }
//
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, kSizeRatio(225))];
    
    self.exitBtn = [UIButton buttonWithType:0];
    
    self.exitBtn.frame = CGRectMake(0, kSizeRatio(30), kSizeRatio(573), kSizeRatio(90));
    
    self.exitBtn.centerX = self.footView.centerX;
    
    self.exitBtn.backgroundColor = [Config colorWithHexString:@"#3bad6a" WithAlpha:1];
    
    self.exitBtn.layer.cornerRadius = kSizeRatio(15);
    self.exitBtn.layer.masksToBounds = true;
    
    [self.exitBtn setTitle:@"退出登录" forState:(UIControlStateNormal)];
    [self.exitBtn addTarget:self action:@selector(exitBtnHandler) forControlEvents:(UIControlEventTouchUpInside)];
    [self.exitBtn.titleLabel setFont:[UIFont systemFontOfSize: 14]];
    [self.exitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    
    [self.footView addSubview:self.exitBtn];
    
    
    self.mainTableView.tableFooterView = self.footView;
    
    __weak typeof(self) weakSelf = self;
    self.HeaderView = [[ZHMyTableHeaderView alloc] initWithFrame:CGRectZero];
    
    self.HeaderView.frame = CGRectMake(0,  0,[UIScreen mainScreen].bounds.size.width,  200);
    self.HeaderView.YingYeButtonBlock = ^{
        [weakSelf changeStatusTouch];
    };
    self.HeaderView.announcementButtonBlock = ^{
        AddNotice *VC = [[AddNotice alloc]initWithNotice:self.gongGaoStr];
        [weakSelf.navigationController pushViewController:VC animated:YES];
    };
    self.HeaderView.ChangYingYeTimeButtonBlock = ^{
        //修改营业时间
        NSArray *time = @[@"0:00", @"0:30", @"1:00", @"1:30", @"2:00", @"2:30", @"3:00", @"3:30",@"4:00", @"4:30",@"5:00", @"5:30",@"6:00", @"6:30",@"7:00", @"7:30",@"8:00", @"8:30",@"9:00", @"9:30",@"10:00", @"10:30",@"11:00", @"11:30",@"12:00", @"12:30",@"13:00", @"13:30",@"14:00", @"14:30",@"15:00", @"15:30",@"16:00", @"16:30",@"17:00", @"17:30",@"18:00", @"18:30",@"19:00", @"19:30",@"20:00", @"20:30",@"21:00", @"21:30",@"22:00", @"22:30",@"23:00", @"23:30"];
        NSArray *dataSources = @[time, time];
        [CGXPickerView showStringPickerWithTitle:@"修改营业时间" DataSource:dataSources DefaultSelValue:@[@"0",@"0"] IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
            
            NSArray *array = [NSArray arrayWithArray:selectValue];
            NSString * open_time = [array[0] isEqualToString: @"0"]? @"0:00":array[0];
            NSString * close_time = [array[1] isEqualToString: @"0"]? @"0:00":array[1];
            [weakSelf showHUD];
            AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
            NSDictionary* arg = @{
                                  @"ince":@"set_shop_open_time",
                                  @"sid":[UserModel sharedInstanced].ru_Id,
                                  @"open_time": open_time,
                                  @"close_time":close_time
                                  };
            [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                [WMHelper outPutJsonString:responseObject];
                NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                if(flag == 200){
                    
                    LiveUser *live = [ShopConfig myProfile];
                    live.open_time = open_time;
                    live.close_time = close_time;
                    [ShopConfig updateProfile:live];
                    [weakSelf.HeaderView updateHeadData];
                    [weakSelf hidHUD];
                }else{
                    
                    [weakSelf hidHUD:[responseObject objectForKey:@"msg"]];
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error)  {
                [weakSelf hidHUD:@"网络异常"];
            }];
            
        }];

    };
    //    view.frame = CGRectMake(0,  0,kScreenWidth,  kSizeRatio(351));
    self.mainTableView.tableHeaderView = self.HeaderView;
    
}

- (UITableView *)mainTableView{
    
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    }
    
    
    return _mainTableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return [self.dataArr[@"section1"] count];
    }else{
        return [self.dataArr[@"section2"] count];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 13)];
    footView.backgroundColor =[UIColor clearColor];
    return footView;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 13)];
        footView.backgroundColor =[UIColor clearColor];
        return footView;
    } else {
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 13;
    } else {
        return 0.00001;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 13;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellId = [NSString stringWithFormat:@"ZHMyItemTableViewCell"];
    ZHMyItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[ZHMyItemTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
    NSDictionary *dic;
    if (indexPath.section == 0) {
        dic = self.dataArr[@"section1"][indexPath.row];
    }else{
        dic = self.dataArr[@"section2"][indexPath.row];

    }
    
    cell.imgView.image = [UIImage imageNamed:dic[@"img"]];
    cell.titleLB.text = dic[@"title"];
    
    if ([dic[@"title"] isEqualToString:@"联系业务经理"] ||
        [dic[@"title"] isEqualToString:@"消息设置"]) {
        cell.lineView.hidden = YES;
    }else{
        cell.lineView.hidden = false;

    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                {
                    //结算信息
                    SettlementInformationViewController* controller = [[SettlementInformationViewController alloc]init];
                    [self.navigationController pushViewController:controller animated:YES];
                }
                break;
            case 1:
            {
                
                //我的钱包
                Account* controller = [[Account alloc]init];
                controller.dataDic = [NSDictionary dictionaryWithDictionary:self.dataDic];
                [self.navigationController pushViewController:controller animated:YES];
                
            }
                break;
            case 2:
            {
                //联系业务经理
                
                AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
                NSDictionary* arg = @{@"ince":@"get_shop_info",@"sid":[UserModel sharedInstanced].ru_Id};
                [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        NSDictionary* dict = [responseObject objectForKey:@"data"];
                        
                        NSMutableString * string = [[NSMutableString alloc] initWithFormat:@"tel:%@",dict[@"tel"]];
                        UIWebView * callWebview = [[UIWebView alloc] init];
                        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:string]]];
                        [self.view addSubview:callWebview];
                        
                        
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error)  {
                    [self hidHUD:@"网络异常"];
                }];
                
            }
                break;
            default:
                break;
        }
    }else{
        switch (indexPath.row) {
            case 0:
            {
                //门店设置
                
                StroeMessageViewController* controller = [[StroeMessageViewController alloc]init];
                [self.navigationController pushViewController:controller animated:YES];
            }
                break;
            case 1:
            {
                //接单设置
                ReceivingOrderViewController* controller = [[ReceivingOrderViewController alloc] init];
                controller.isJieDanSet = YES;
                [self.navigationController pushViewController:controller animated:YES];
            }
                break;
            case 2:
            {
                //打印机
                //接单设置
                ReceivingOrderViewController* controller = [[ReceivingOrderViewController alloc] init];
               
                [self.navigationController pushViewController:controller animated:YES];
            }
                break;
            case 3:
            {
                //消息设置
                MessgerSettingViewController* controller = [[MessgerSettingViewController alloc] init];
                
                [self.navigationController pushViewController:controller animated:YES];
                
            }
                break;
                
            default:
                break;
        }
    }
    
}

-(void)changeStatusTouch{
    
    [self showHUD];
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{@"ince":@"set_shop_open",@"sid":[UserModel sharedInstanced].ru_Id,@"close":[[ShopConfig getStatus] isEqualToString:@"1"]?@"0":@"1"};
    
    NSLog(@"状态值   r%@",[ShopConfig getStatus]);
    [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
           NSString *st =  [responseObject objectForKey:@"close"];
            LiveUser *live = [ShopConfig myProfile];
            live.status = st;
            [ShopConfig updateProfile:live];
            [self.HeaderView updateHeadData];
            [self hidHUD];
        }else{
            
            [self hidHUD:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        [self hidHUD:@"网络异常"];
    }];
    
}


- (void)exitBtnHandler{
    //退出登录
    [ShopConfig clearProfile];
    MMember* entity = self.Identity.userInfo;
    entity.isLogin = NO;
    Boolean flag= [NSKeyedArchiver archiveRootObject:entity toFile:[WMHelper archiverPath]];
    if(flag){
        [self logoutJPush:entity.userID];
        self.tabBarController.selectedIndex = 0;
    }else{
        
    }
    
    
}
#pragma mark =====================================================  private method
-(void)logoutJPush:(NSString*)userID{
    
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@"消息推送退出%tu,%@,%tu",iResCode,iAlias,seq);
        if(iResCode == 0){
            
        }else{
            UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"消息推送退出失败!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
    } seq:1];
    
    
    //    __autoreleasing NSMutableSet *tags = [NSMutableSet set];
    //    __autoreleasing NSString *alias = @"";
    //
    //    [JPUSHService setTags:tags alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
    //        NSLog(@"TagsAlias回调:\n iResCode:%d  iAlias:%@",iResCode,iAlias);
    //        if(iResCode == 0){
    //
    //        }else{
    //            UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"消息推送退出失败!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    //            [alert show];
    //        }
    //    }];
}


- (void)getData{
    
    //"ince":"getshopinfo","sid":"101","rrbl_shop_id":"101"

    NSDictionary* arg = @{@"ince":@"getshopinfo",@"shop_id":[UserModel sharedInstanced].ru_Id};
    [NetRepositories netConfirm:arg complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        if(react == NetResponseSuccess){
           
            [self.HeaderView updateHeadData];
            
            NSDictionary *dic = response[@"data"];
            self.dataDic = [NSDictionary dictionaryWithDictionary:dic];
            self.gongGaoStr =[dic objectForKey:@"shop_remark"];
            [self.HeaderView updateNewHeadDataWith:dic];
        }else if (react == NetResponseFail){
           
        }else{
           
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
